﻿using System.Collections.ObjectModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace 随心笔记1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private ObservableCollection<MindMapNode> _nodes = new ObservableCollection<MindMapNode>();
        
        private MindMapNode _draggedNode;
        private Point _dragOffset;

        private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var element = e.Source as FrameworkElement;
            if (element?.DataContext is MindMapNode node)
            {
                _draggedNode = node;
                _dragOffset = e.GetPosition(element);
                element.CaptureMouse();
            }
        }

        private void Canvas_MouseMove(object sender, MouseEventArgs e)
        {
            if (_draggedNode != null)
            {
                var newPos = e.GetPosition(MainCanvas) - _dragOffset;
                // 更新节点位置
                _draggedNode.Position = (Point)newPos;
                // 更新UI（使用Canvas.SetLeft/Top）
                var element = FindVisualElement(_draggedNode);
                Canvas.SetLeft(element, newPos.X);
                Canvas.SetTop(element, newPos.Y);
                // 更新连接线
                UpdateConnections();
            }
        }

        private FrameworkElement FindVisualElement(MindMapNode node)
        {
            foreach (var child in MainCanvas.Children.OfType<FrameworkElement>())
            {
                if (child.DataContext is MindMapNode currentNode && currentNode.Id == node.Id)
                {
                    return child;
                }
            }
            return null;
        }

        private void UpdateConnections()
        {
            // 清除旧连接线（标记为连接线的元素）
            var connectionsToRemove = MainCanvas.Children
                .OfType<Path>()
                .Where(p => p.Tag?.ToString() == "Connection")
                .ToList();

            foreach (var conn in connectionsToRemove)
            {
                MainCanvas.Children.Remove(conn);
            }

            // 重新绘制所有连接
            foreach (var node in _nodes)
            {
                foreach (var childId in node.Children)
                {
                    var childNode = _nodes.FirstOrDefault(n => n.Id == childId);
                    if (childNode != null)
                    {
                        var startPoint = GetConnectionPoint(node, true);  // 父节点出口
                        var endPoint = GetConnectionPoint(childNode, false); // 子节点入口
                        var connectionPath = CreateConnection(startPoint, endPoint);
                        connectionPath.Tag = "Connection"; // 添加标记
                        MainCanvas.Children.Add(connectionPath);
                    }
                }
            }
        }

        // 获取连接点坐标（带偏移）
        private Point GetConnectionPoint(MindMapNode node, bool isOutputPoint)
        {
            var element = FindVisualElement(node);
            if (element == null) return new Point();

            var centerX = node.Position.X + node.Size.Width / 2;
            var centerY = node.Position.Y + node.Size.Height / 2;

            return isOutputPoint
                ? new Point(node.Position.X + node.Size.Width, centerY) // 右侧中点
                : new Point(node.Position.X, centerY); // 左侧中点
        }

        private Path CreateConnection(Point start, Point end)
        {
            var path = new Path
            {
                Stroke = Brushes.Black,
                StrokeThickness = 2,
                Data = new PathGeometry
                {
                    Figures =
                    {
                        new PathFigure
                        {
                            StartPoint = start,
                            Segments =
                            {
                                new BezierSegment(
                                    start + new Vector(50, 0), // 控制点1
                                    end - new Vector(50, 0),   // 控制点2
                                    end,
                                    true)
                            }
                        }
                    }
                }
            };
            return path;
        }

        // 缩放整个画布
        private void ApplyZoom(double scale)
        {
            var transform = new ScaleTransform(scale, scale);
            MainCanvas.LayoutTransform = transform;
        }

        // 旋转单个节点
        private void RotateNode(MindMapNode node, double angle)
        {
            var element = FindVisualElement(node);
            element.RenderTransform = new RotateTransform(angle);
        }

        private void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
        {
        }
    }

    public class MindMapNode
    {
        public Guid Id { get; } = Guid.NewGuid();
        public string Text { get; set; }
        public Point Position { get; set; }
        public Size Size { get; set; } = new Size(100, 60);
        public List<Guid> Children { get; } = new List<Guid>();
    }

    public class VirtualizingCanvas : VirtualizingPanel
    {
        // 实现自定义虚拟化逻辑，仅渲染可见区域元素
        protected override Size MeasureOverride(Size availableSize)
        {
            // 计算可见项
            return base.MeasureOverride(availableSize);
        }
    }
}